package com.project.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.project.model.MemberModel;
import com.project.model.RedPacketModel;
import com.project.model.ShopModel;
import com.project.model.TradeDetailModel;
import com.project.service.MemberService;
import com.project.service.RedPacketService;
import com.project.service.ShopService;
import com.project.service.TradeDetailService;
import com.project.utils.DistanceUtil;
import com.project.utils.GlobalDefinition;
import com.project.utils.TokenProccessor;
import com.project.vo.DistanceVo;

@Controller
@RequestMapping(value = "")
public class RedPacketController {
	private static Logger logger = LoggerFactory.getLogger(RedPacketController.class);
	
	private final String moduleName = "packet";
	
	@Autowired
	private RedPacketService redPacketService;
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private TradeDetailService tradeDetailService;
	
	@Autowired
	private MemberService memberService;
	
//	@RequestMapping("/toSearchRedPacket")
//	public ModelAndView toSearchRedPacket(DistanceVo distanceVo) {
//		ModelAndView view = new ModelAndView();
//		if (StringUtils.isEmpty(distanceVo.getDistance())) {
//			distanceVo.setDistance(GlobalDefinition.DEFAULT_DISTANCE);
//		}
//		Map<String, Object> condition = DistanceUtil.getAround(distanceVo.getLatitude(), distanceVo.getLongitude(), distanceVo.getDistance());
//		condition.put("size", GlobalDefinition.DEFAULT_SIZE);
//		
//		List<ShopModel> list = shopService.getListByDistance(condition);
//		view.addObject("shopList", list);
//		view.addObject("distanceVo", distanceVo);
//		view.setViewName("/jsp/searchRedPacket.jsp");
//		return view;
//	}
//	
//	@RequestMapping("/getRedPacket")
//	public @ResponseBody Map<String, Object> getRedPacket(DistanceVo distanceVo, HttpSession session) {
//		Map<String, Object> condition = DistanceUtil.getAround(distanceVo.getLatitude(), distanceVo.getLongitude(), distanceVo.getDistance());
//		condition.put("size", GlobalDefinition.DEFAULT_SIZE);
//		// FIXME 会员ID
//		Map<String, Object> result = new HashMap<String, Object>();
//		if (null != session.getAttribute("userId")) {
//			condition.put("memberId", (int)session.getAttribute("userId"));
//			// result = redPacketService.getRedPacket(condition);
//		} else {
//			result.put("code", "-1");
//			result.put("msg", "登录失效，请重新登录");
//		}
//		
//		return result;
//	}
	
	// 跳入红包扫描页面
	@RequestMapping(moduleName + "/searchRedPacket")
	public ModelAndView searchRedPacket(HttpServletRequest request) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		
		ModelAndView mav = new ModelAndView();
		if (null == request.getSession().getAttribute("userId")) {
			// request.getSession().setAttribute("loginPage", "/member/"+moduleName+"/searchRedPacket");
			mav.addObject("page", "/member/"+moduleName+"/searchRedPacket");
			mav.setViewName("/again_login.jsp");
			return mav;
		}
		int userid = (int)request.getSession().getAttribute("userId");
		MemberModel memberModel = memberService.getMemberModelById(userid);
		mav.addObject("memberModel", memberModel);
		mav.setViewName("/searchRedPacket.jsp");
		
		String token = TokenProccessor.getInstance().makeToken();//创建令牌
		request.getSession().setAttribute("token", token);
		// httpSession.setAttribute("module_name", "member");
		// httpSession.setAttribute("page_name", "member");
		return mav;
	}
	
	// 获取红包
	@RequestMapping(moduleName + "/coordinate_range_list")
	public @ResponseBody Map<String, Object> coordinateRangeList(DistanceVo distanceVo, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isEmpty(distanceVo.getDistance())) {
			distanceVo.setDistance(GlobalDefinition.DEFAULT_DISTANCE);
		}
		int userid = 0;
		if (null != session.getAttribute("userId")) {
			userid = (int)session.getAttribute("userId");
			MemberModel memberModel = memberService.getMemberModelById(userid);
			if (memberModel.getSearch_num() < 1) {
				map.put("code", "1");
				map.put("msg", "当日扫描红包的次数已用完");
			} else {
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("user_id", userid);
				List<ShopModel> shop_list = shopService.getListAll(condition);
				// List<ShopModel> list = shopService.getListByDistance(condition);
				List<ShopModel> list = new ArrayList<ShopModel>();
				if (shop_list.size() > 0) {
					for (int i=0; i<shop_list.size(); i++) {
						String distance = String.valueOf(shop_list.get(i).getRanges()*1000);
						Map<String, Object> map_distance = DistanceUtil.getAround(shop_list.get(i).getLatitude(), shop_list.get(i).getLongitude(), distance);
						
						double my_longitude = Double.parseDouble(distanceVo.getLongitude());
						double my_latitude = Double.parseDouble(distanceVo.getLatitude());
						
						
						double longitude_min = Double.parseDouble(map_distance.get("longitude_min").toString());
						double longitude_max = Double.parseDouble(map_distance.get("longitude_max").toString());
						double latitude_min = Double.parseDouble(map_distance.get("latitude_min").toString());
						double latitude_max = Double.parseDouble(map_distance.get("latitude_max").toString());
						if (my_longitude >= longitude_min && my_longitude <= longitude_max && my_latitude >= latitude_min && my_latitude <= latitude_max) {
							list.add(shop_list.get(i));
						}
					}
					
					if (list.size() > 0) {
						int shopNum = 9;
						List<ShopModel> newList = new ArrayList<ShopModel>();
						Random rd=new Random();
						for (int i=0; i<list.size(); i++) {
							int rdm = rd.nextInt(list.size());
							if (newList.size() == shopNum) {
								break;
							} else {
								newList.add(list.get(rdm));
							}
						}
						Map<String, Object> result = redPacketService.getRedPacket(list, userid);
						map.put("redPacket", result);
					}
				}
				
				memberModel.setSearch_num(1);
				memberService.updateSearchNumBySubtract(memberModel);
				
				map.put("code", "0");
				map.put("shopList", list);
			}
		} else {
			map.put("code", "-1");
			map.put("msg", "登录失效，请重新登录");
		}
		return map;
	}
	
	// 绑定红包
	@RequestMapping(moduleName + "/bindRedPacket")
	public ModelAndView bindRedPacket(RedPacketModel redPacket, HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		
		String token = "";
		if (null != request.getSession().getAttribute("token")) {
			token = (String)request.getSession().getAttribute("token");
		}
		String contrast_token = request.getParameter("token");
		if (token.equals(contrast_token)) {
			if (null != request.getSession().getAttribute("userId")) {
				// FIXME 设置会员ID
				redPacket.setMemberId((int)request.getSession().getAttribute("userId"));
				redPacket.setStatus(2);
				redPacketService.bindRedPacket(redPacket);
				redPacket = redPacketService.getRedPacketModelById(redPacket.getId());
				
				MemberModel memberModel = new MemberModel();
				memberModel.setId((int)request.getSession().getAttribute("userId"));
				memberModel.setCoin_num(redPacket.getPrice().doubleValue());
				memberService.updateCoinNumByAddition(memberModel);
				
				memberModel = memberService.getMemberModelById((int)request.getSession().getAttribute("userId"));
				
				TradeDetailModel tradeDetailModel = new TradeDetailModel();
				tradeDetailModel.setMember_id((int)request.getSession().getAttribute("userId"));
				tradeDetailModel.setShop_id(0);
				tradeDetailModel.setEvent_id(redPacket.getEventId());
				tradeDetailModel.setAmount(redPacket.getPrice().doubleValue());
				tradeDetailModel.setAfter_amount(memberModel.getCoin_num());
				tradeDetailModel.setType(1); // 获取店铺红包
				tradeDetailService.insert(tradeDetailModel);
				
				view.addObject("redPacket", redPacket);
				view.setViewName("/open_red_packet.jsp");
				request.getSession().removeAttribute("token");
			} else {
				// 登录失败，应该调用微信登录接口进行登录，然后在跳入拆开红包页面
				// request.getSession().setAttribute("loginPage", "/bindRedPacket");
				view.addObject("page", "/bindRedPacket?id="+redPacket.getId() + "&token="+contrast_token);
				view.setViewName("/again_login.jsp");
			}
		} else {
			redPacket = redPacketService.getRedPacketModelById(redPacket.getId());
			view.addObject("redPacket", redPacket);
			view.setViewName("/open_red_packet.jsp");
		}
		return view;
	}
	
	// 红包退回
	@RequestMapping(moduleName + "/update_coin_num")
	public @ResponseBody Map<String, Object> updateCoinNum(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String redPacketId = request.getParameter("redPacketId");
		String eventId = request.getParameter("eventId");
		if (null != redPacketId && !"".equals(redPacketId.trim()) && !"0".equals(redPacketId.trim())) {
			RedPacketModel redPacketModel = redPacketService.getRedPacketModelById(Integer.parseInt(redPacketId.trim()));
			if (null != redPacketModel && redPacketModel.getPrice().doubleValue() > 0) {
				if (null != id && !"".equals(id.trim()) && !"0".equals(id.trim())) {
					ShopModel shopModel = new ShopModel();
					shopModel.setUser_id(Integer.parseInt(id));
					shopModel.setMoney(redPacketModel.getPrice());
					if (shopService.updateAddMoneyByUserId(shopModel) > 0) {
						if (null != eventId && !"".equals(eventId.trim()) && !"0".equals(eventId.trim())) {
							// shopModel = shopService.getByUserId(Integer.parseInt(id));
							List<ShopModel> shopModels = shopService.getByUserId(Integer.parseInt(id));
							if (null != shopModels && shopModels.size() > 0) {
								shopModel = shopModels.get(0);
							}
							
							TradeDetailModel tradeDetailModel = new TradeDetailModel();
							tradeDetailModel.setMember_id(0);
							tradeDetailModel.setShop_id(Integer.parseInt(id.trim()));
							tradeDetailModel.setEvent_id(Integer.parseInt(eventId.trim()));
							tradeDetailModel.setAmount(redPacketModel.getPrice().doubleValue());
							tradeDetailModel.setAfter_amount(shopModel.getMoney().doubleValue());
							tradeDetailModel.setType(2); // 红包退回
							tradeDetailService.insert(tradeDetailModel);
						} else {
							map.put("code", "-1");
							map.put("msg", "更新失败，没有找到活动");
						}
					} else {
						map.put("code", "-1");
						map.put("msg", "更新失败，更新用户金币失败");
					}
				} else {
					map.put("code", "-1");
					map.put("msg", "更新失败 ，用户不存在");
				}
			} else {
				map.put("code", "-1");
				map.put("msg", "更新失败，没有找到红包");
			}
		} else {
			map.put("code", "-1");
			map.put("msg", "更新失败，没有找到红包");
		}
		
		map.put("code", "0");
		map.put("msg", "更新成功");
		
		return map;
	}
}